package com.lwl.concurrency.thread;

/**
 * @author liwenlong - 2018/3/25 21:11
 */
public class GoodSuspend {

    public static final Object object = new Object();

    public static class ChangeObjectThread extends Thread {
        volatile boolean suspendme = false;

        /**
         * 线程挂起
         */
        public void suspendMe() {
            suspendme = true;
        }

        /**
         * 继续执行
         */
        public void resumeMe() {
            suspendme = false;
            synchronized (this) {
                notify();
            }
        }

        @Override
        public void run() {
            while (true) {
                synchronized (this) {
                    while (suspendme) {
                        try {
                            System.out.println("wait start");
                            wait();
                            System.out.println("wait end");
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                }
                synchronized (object) {
                   System.out.println("in ChangeObjectThread");
                }
                Thread.yield();
            }
        }
    }


    public static class ReadObjectThread extends Thread{
        @Override
        public void run() {
            while(true){
                synchronized (object){
                    System.out.println("in ReadObjectThread");
                }
                Thread.yield();
            }
        }
    }


    public static void main(String[] args) throws InterruptedException {

        ChangeObjectThread t1 = new ChangeObjectThread();
        ReadObjectThread t2 = new ReadObjectThread();

        t1.start();
        t2.start();

        Thread.sleep(1000);
        t1.suspendMe();
        System.out.println("suspend t1 2 sec");

        Thread.sleep(2000);
        System.out.println("resume t1");
        t1.resumeMe();

    }



}
